package com.qg.oss.core.aliyun.client;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.qg.oss.core.CommonClient;
import com.qg.oss.core.aliyun.config.AliyunOSSProperties;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author QG
 * @Date 2023/6/12 16:06
 * @description 阿里云oss客户端实现类
 **/
//@Component
public class AliyunOSSClient implements CommonClient {

    private static final String PREFIX = "https://";

    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;

    @Autowired
    private OSS ossClient;

    @Override
    public String uploadFile(String fileName, String bucketName, byte[] bytes, String folder, String objectName) {
        String fileMd5 = DigestUtils.md5Hex(bytes);
        if (StringUtils.isEmpty(objectName)) {
            objectName = fileMd5 + fileName.substring(fileName.lastIndexOf("."));
        }
        if (StringUtils.isEmpty(folder)) {
            folder = getFileFolder(new Date(), true, true, true);
        } else if (!folder.contains("/")) {
            folder = folder + "/";
        }
        objectName = folder + objectName;
        //存储文件到oss中
        // 创建PutObjectRequest对象。
        try {
            uploadFileToOSS(bytes, bucketName, objectName);
            //返回文件访问路径
            return PREFIX + aliyunOSSProperties.getEndpoint() + "/" + objectName;
        } catch (OSSException | BeansException | ClientException e) {
            throw new RuntimeException("文件上传异常");
        }
    }


    private String getFileFolder(Date date, boolean year, boolean month, boolean day) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy:MM:dd");
        String dateFormat = format.format(new Date());
        String[] split = dateFormat.split(":");
        StringBuilder sb = new StringBuilder();
        if (year) {
            sb.append(split[0]);
            sb.append("/");
        }
        if (month) {
            sb.append(split[1]);
            sb.append("/");
        }
        if (day) {
            sb.append(split[2]);
            sb.append("/");
        }
        return sb.toString();
    }

    @Override
    public void uploadFileToOSS(byte[] bytes, String bucketName, String objectName) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(bytes));
        ossClient.putObject(putObjectRequest);
    }


}
